package code.BinaryTree;

import struct.Tree;
import struct.TreeNode;

public class ChangeNode {
	public static void main(String[] args) {
		ChangeNode changeNode = new ChangeNode();
		TreeNode treeNode = Tree.constructTree("[2,4,7,1,3,6,9]");

//		TreeNode treeNode1 = changeNode.removeLeafNodes(treeNode, 2);

		TreeNode node = changeNode.invertTree2(treeNode);
		System.out.println(node);
	}

	//暴力解法
	public TreeNode removeLeafNodes(TreeNode root, int target) {
		if (root == null) {
			return null;
		}
		root.left = removeLeafNodes(root.left, target);
		root.right = removeLeafNodes(root.right, target);
		if (root.left == null && root.right == null && target == root.val) {
			root = null;
		}
		return root;
	}


	//226. 翻转二叉树
	public TreeNode invertTree(TreeNode root) {
		if (root == null) {//0.终止条件直接返回
			return null;
		}
		TreeNode tmp = root.left;//1.交换节点
		root.left = root.right;
		root.right = tmp;

		invertTree(root.left);//2.让左子树内部交换节点
		invertTree(root.right);//3.让左子树内部交换节点
		return root;//4.返回修改之后的节点
	}

	public TreeNode invertTree2(TreeNode root) {
		if (root == null) {
			return null;
		}

		TreeNode left = invertTree2(root.left);
		TreeNode right = invertTree2(root.right);
		root.left = right;
		root.right = left;
		return root;
	}
}
